<template>
  <div class="order-detail-container">
    <div class="header">
      <el-button type="text" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h1>订单详情</h1>
    </div>
    
    <div v-if="loading" class="loading">
      <el-loading v-model="loading" text="加载中..." />
    </div>
    
    <div v-else-if="order" class="order-content">
      <!-- 订单状态卡片 -->
      <div class="status-card">
        <div class="status-header">
          <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
          <span class="order-number">订单编号：{{ order.id }}</span>
        </div>
        <div class="status-info">
          <p>下单时间：{{ formatDate(order.createdAt) }}</p>
          <p v-if="order.updatedAt">更新时间：{{ formatDate(order.updatedAt) }}</p>
        </div>
        <div class="status-actions" v-if="order.status === 'pending'">
          <el-button type="primary" @click="payOrder">立即支付</el-button>
          <el-button type="default" @click="cancelOrder">取消订单</el-button>
        </div>
      </div>
      
      <!-- 商品列表 -->
      <div class="section">
        <h2>商品信息</h2>
        <div class="product-list">
          <div class="product-item" v-for="item in order.orderItems" :key="item.id">
            <img :src="item.productImage" alt="{{ item.productName }}" class="product-image" />
            <div class="product-info">
              <div class="product-name">{{ item.productName }}</div>
              <div class="product-price">¥{{ item.price.toFixed(2) }}</div>
              <div class="product-quantity">x{{ item.quantity }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 配送信息 -->
      <div class="section">
        <h2>配送信息</h2>
        <div class="shipping-info">
          <p><span class="label">配送地址：</span>{{ order.shippingAddress }}</p>
        </div>
      </div>
      
      <!-- 支付信息 -->
      <div class="section">
        <h2>支付信息</h2>
        <div class="payment-info">
          <p><span class="label">支付方式：</span>{{ getPaymentMethodText(order.paymentMethod) }}</p>
          <p><span class="label">支付状态：</span>{{ order.status === 'paid' || order.status === 'shipped' || order.status === 'delivered' ? '已支付' : '未支付' }}</p>
        </div>
      </div>
      
      <!-- 订单金额 -->
      <div class="section">
        <h2>订单金额</h2>
        <div class="order-amount">
          <div class="amount-item">
            <span class="label">商品总价：</span>
            <span class="value">¥{{ calculateSubtotal().toFixed(2) }}</span>
          </div>
          <div class="amount-item">
            <span class="label">运费：</span>
            <span class="value">¥0.00</span>
          </div>
          <div class="amount-item total">
            <span class="label">订单总价：</span>
            <span class="value">¥{{ order.totalAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="actions-bottom" v-if="order.status === 'pending'">
        <el-button type="default" @click="goBack">返回订单列表</el-button>
        <div class="right-actions">
          <el-button type="default" @click="cancelOrder">取消订单</el-button>
          <el-button type="primary" @click="payOrder">立即支付</el-button>
        </div>
      </div>
    </div>
    
    <div v-else class="error">
      <el-empty description="订单不存在或已被删除" />
      <el-button type="primary" @click="goBack">返回订单列表</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { ArrowLeft } from '@element-plus/icons-vue';
import { orderService } from '../../api/orderService';
import type { Order } from '../../api/orderService';

const router = useRouter();
const route = useRoute();
const order = ref<Order | null>(null);
const loading = ref(false);

// 获取订单ID
const orderId = computed(() => {
  const id = Number(route.params.id);
  // 检查ID是否有效
  return isNaN(id) ? 0 : id;
});

// 获取订单详情
const fetchOrderDetail = async () => {
  // 检查订单ID是否有效
  if (!orderId.value || orderId.value <= 0) {
    ElMessage.error('无效的订单ID');
    return;
  }
  
  loading.value = true;
  try {
    const response = await orderService.getOrder(orderId.value);
    
    // 检查响应是否为有效的JSON数据
    if (response && typeof response === 'object') {
      // 确保响应数据存在且为对象
      if (response.data && typeof response.data === 'object') {
        order.value = response.data as Order;
      } else {
        throw new Error('Invalid response data format');
      }
    } else {
      throw new Error('Invalid response format');
    }
  } catch (error) {
    // 处理各种可能的错误情况
    if (error instanceof Error && error.message.includes('Unexpected token')) {
      ElMessage.error('服务器返回错误，请检查网络连接或稍后重试');
    } else {
      ElMessage.error('获取订单详情失败');
    }
    console.error('获取订单详情失败:', error);
    order.value = null;
  } finally {
    loading.value = false;
  }
};

// 计算商品总价
const calculateSubtotal = () => {
  if (!order.value) return 0;
  return order.value.orderItems.reduce((total, item) => {
    return total + (item.price * item.quantity);
  }, 0);
};

// 支付订单
const payOrder = async () => {
  if (!order.value) return;
  try {
    await orderService.processPayment(order.value.id);
    ElMessage.success('支付成功');
    fetchOrderDetail(); // 重新获取订单详情
  } catch (error) {
    ElMessage.error('支付失败');
    console.error('支付失败:', error);
  }
};

// 取消订单
const cancelOrder = async () => {
  if (!order.value) return;
  try {
    await orderService.cancelOrder(order.value.id);
    ElMessage.success('订单已取消');
    fetchOrderDetail(); // 重新获取订单详情
  } catch (error) {
    ElMessage.error('取消订单失败');
    console.error('取消订单失败:', error);
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).format(date);
};

// 获取订单状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待支付',
    paid: '已支付',
    shipped: '已发货',
    delivered: '已完成',
    cancelled: '已取消'
  };
  return statusMap[status] || status;
};

// 获取订单状态标签类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'primary',
    paid: 'success',
    shipped: 'info',
    delivered: 'success',
    cancelled: 'danger'
  };
  return typeMap[status] || 'default';
};

// 获取支付方式文本
const getPaymentMethodText = (method: string) => {
  const methodMap: Record<string, string> = {
    wechat: '微信支付',
    alipay: '支付宝',
    card: '银行卡支付'
  };
  return methodMap[method] || method;
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 组件挂载时获取订单详情
onMounted(() => {
  fetchOrderDetail();
});
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;
}

.header h1 {
  font-size: 20px;
  color: #333;
  margin: 0 0 0 10px;
}

.loading,
.error {
  padding: 60px 0;
  text-align: center;
}

.order-content {
  max-width: 1200px;
  margin: 0 auto;
}

.status-card {
  background-color: #fafafa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #e6e6e6;
}

.status-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.status-header .el-tag {
  margin-right: 15px;
  font-size: 16px;
  padding: 8px 16px;
}

.order-number {
  font-size: 14px;
  color: #666;
}

.status-info {
  margin-bottom: 15px;
}

.status-info p {
  margin: 5px 0;
  font-size: 14px;
  color: #666;
}

.status-actions {
  display: flex;
  gap: 10px;
}

.section {
  margin-bottom: 30px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  overflow: hidden;
}

.section h2 {
  font-size: 16px;
  color: #333;
  margin: 0;
  padding: 15px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #e6e6e6;
}

.product-list {
  padding: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-right: 20px;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
}

.product-price {
  font-size: 14px;
  color: #ff6700;
  margin-bottom: 5px;
}

.product-quantity {
  font-size: 14px;
  color: #666;
}

.shipping-info,
.payment-info {
  padding: 20px;
}

.shipping-info p,
.payment-info p {
  margin: 10px 0;
  font-size: 14px;
}

.label {
  color: #666;
  margin-right: 10px;
}

.order-amount {
  padding: 20px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-size: 14px;
}

.amount-item.total {
  font-weight: bold;
  font-size: 16px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.amount-item.total .value {
  color: #ff6700;
}

.actions-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  margin-top: 30px;
  border-top: 1px solid #e6e6e6;
}

.right-actions {
  display: flex;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .order-detail-container {
    padding: 20px;
  }
  
  .product-item {
    padding: 15px;
  }
  
  .product-image {
    width: 80px;
    height: 80px;
  }
}

@media (max-width: 992px) {
  .status-card {
    padding: 20px;
  }
  
  .product-item {
    padding: 12px;
  }
  
  .product-image {
    width: 70px;
    height: 70px;
  }
  
  .section {
    padding: 15px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-detail-container {
    padding: 10px;
  }
  
  .status-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .product-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    padding: 15px;
  }
  
  .product-image {
    width: 100%;
    height: auto;
    max-height: 200px;
  }
  
  .actions-bottom {
    flex-direction: column;
    gap: 15px;
  }
  
  .right-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .section {
    padding: 15px;
  }
  
  .shipping-info p,
  .payment-info p {
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .header h1 {
    font-size: 20px;
  }
  
  .status-card {
    padding: 15px;
  }
  
  .order-number {
    font-size: 14px;
  }
  
  .product-item {
    padding: 10px;
  }
  
  .product-name {
    font-size: 16px;
  }
  
  .product-price,
  .product-quantity {
    font-size: 14px;
  }
  
  .amount-item {
    font-size: 13px;
  }
  
  .amount-item.total {
    font-size: 15px;
  }
  
  .amount-item.total .value {
    font-size: 16px;
  }
  
  .actions-bottom {
    padding: 15px 0;
  }
  
  .right-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .right-actions .el-button {
    width: 100%;
  }
}
</style>